package com.micromall.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.micromall.common.base.BaseController;
import com.micromall.common.exception.BusiException;
import com.micromall.common.utils.*;
import com.micromall.model.BusiCart;
import com.micromall.model.BusiCartDetailItem;
import com.micromall.model.BusiProduct;
import com.micromall.model.MiMember;
import com.micromall.service.IBusiCartDetailItemService;
import com.micromall.service.IBusiCartService;
import com.micromall.service.IBusiProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 购物车表  前端控制器
 * </p>
 * @author Dante Fung
 * @since 2017-07-26
 */
@Controller
@RequestMapping("/busiCart")
public class BusiCartController extends BaseController {

    public static final Logger logger = LoggerFactory.getLogger(BusiCartController.class);

    @Autowired private IBusiCartService busiCartService;

    @Autowired private IBusiCartDetailItemService busiCartDetailItemService;

    @Autowired private IBusiProductService busiProductService;

    @Resource
    private JdbcTemplate jdbcTemplate;
    
    @RequestMapping("/manager")
    public String manager() {
        return "admin/busiCart/busiCartList";
    }


    @PostMapping("/dataGrid")
    @RequestMapping
    public PageInfo dataGrid(BusiCart busiCart, Integer page, Integer rows, String sort,String order) {
        EntityWrapper<BusiCart> ew = new EntityWrapper<BusiCart>();
        ew.setEntity(busiCart);
        Page<BusiCart> pages = getPage(page, rows, sort, order);
        pages = busiCartService.selectPage(pages,ew);
        return pageToPageInfo(pages);
    }
    
    /**
     * 添加页面
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage() {
        return "admin/busiCart/busiCartAdd";
    }

    /**
     * 添加
     * @param 
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public Object add(BusiCart busiCart) {
        busiCart.setCreateTime(DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
        busiCart.setUpdateTime(DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
        busiCart.setDataStatus(Dict.YesOrNo.Yes.getCode());
        boolean b = busiCartService.insert(busiCart);
        if (b) {
            return renderSuccess("添加成功！");
        } else {
            return renderError("添加失败！");
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(String id) {
        BusiCart busiCart = new BusiCart();
        busiCart.setId(id);
        busiCart.setUpdateTime(DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
    busiCart.setDataStatus(Dict.YesOrNo.No.getCode());
        boolean b = busiCartService.updateById(busiCart);
        if (b) {
            return renderSuccess("删除成功！");
        } else {
            return renderError("删除失败！");
        }
    }

    /**
     * 编辑
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(Model model, Long id) {
        BusiCart busiCart = busiCartService.selectById(id);
        model.addAttribute("busiCart", busiCart);
        return "admin/busiCart/busiCartEdit";
    }

    /**
     * 编辑
     * @param 
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Object edit(BusiCart busiCart) {
        busiCart.setUpdateTime(DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
        boolean b = busiCartService.updateById(busiCart);
        if (b) {
            return renderSuccess("编辑成功！");
        } else {
            return renderError("编辑失败！");
        }
    }

    @RequestMapping("/add_do_shoppingCart")
    public String add_do_shoppingCart(HttpServletRequest request,String id){
        HttpSession session =  request.getSession();
//        SysUser user = (SysUser)session .getAttribute("currUser");
        MiMember cuurMiMember = (MiMember)session .getAttribute("cuurMiMember");
        String validateSuocre =request.getParameter("verifySuocrePage");

        if(StringUtils.isBlank(id)){
            throw  new BusiException("商品id为空，没有选择商品");
        }
        BusiProduct bp = busiProductService.selectById(id);
        logger.info("BusiProduct:[{}]", JSONObject.toJSONString(bp));
        //判断是否登录
        if( cuurMiMember != null ){//跳转到购物车列表页面
            //登录了，商品添加到购物车，该用户的购物车增加商品详情项
            logger.info("cuurMiMember:[{}]", JSONObject.toJSONString(cuurMiMember));
            //1.第一次请求也没没有Token，后台生成Token放进域对象，通过重定向再次请求页面
            if (StringUtils.isBlank(validateSuocre)){
                String verifySuocrePage = MD5Util.getMD5String(ValidateUtil.genSmsValidateCode());
                request.getSession().setAttribute("verifySuocrePage", verifySuocrePage);
                request.setAttribute("verifySuocrePage",verifySuocrePage);
                return "redirect:/busiCart/add_do_shoppingCart?id="+id+"&verifySuocrePage="+verifySuocrePage;
            }

            String verifySuocreCache = (String)session.getAttribute("verifySuocrePage");
            //2.如果Token验证不通过，重定向到原页面
            if (!validateSuocre.equalsIgnoreCase(verifySuocreCache)){
                return "redirect:/busiProduct/do_detail_Page?id="+id;
            }
            EntityWrapper<BusiCart> ew = new EntityWrapper<>();
            BusiCart busiCart = new BusiCart();
            busiCart.setMemberNo(cuurMiMember.getMemberNo());
            ew.setEntity(busiCart);
            BusiCart currUserCart = busiCartService.selectOne(ew);
            if(null != currUserCart){
                //当前用户有购物车，添加商品到购物车
                EntityWrapper<BusiCartDetailItem> ew1 = new EntityWrapper();
                BusiCartDetailItem busiCartDetailItem = new BusiCartDetailItem();
                busiCartDetailItem.setCartId(currUserCart.getId());
                //查询状态为有效的清单项
                busiCartDetailItem.setStandy3(Dict.YesOrNo.Yes.getCode());
                //查询产品状态码为1000的清单项
                busiCartDetailItem.setStandy4(Dict.BusiCaer.CartItemStatusCode.NEW.getCode());
                ew1.setEntity(busiCartDetailItem);
                List<BusiCartDetailItem> busiCartDetailItems = busiCartDetailItemService.selectList(ew1);
                //如果该购物车已有该产品，该产品数量+1
                //否则该购物车添加该产品
                if(null != busiCartDetailItems && busiCartDetailItems.size() > 0){
                    //购物车是否有该产品标志
                    Boolean B = false ;
                    for (BusiCartDetailItem bcd : busiCartDetailItems){
                        String prodId = bcd.getProdId();
                        if(id.equals(prodId)){//购物车已有该产品，该产品数量+1
                            int sun =Integer.parseInt(bcd.getSum())+1;
                            bcd.setSum(sun+"");
                            B = busiCartDetailItemService.updateById(bcd);
                            logger.info(JSONObject.toJSONString(bcd) +"的数量为："+ sun );
                            //B = true;
                        }
                    }
                    if(!B){//购物车没有该产品
                        String cartDetailItemId = getCartDetailItemId();
                        busiCartDetailItem.setId(cartDetailItemId);
                        busiCartDetailItem.setSum(1+"");
                        busiCartDetailItem.setCartId(currUserCart.getId());
                        busiCartDetailItem.setProdId(bp.getId());
                        busiCartDetailItem.setProdName(bp.getZhName());
                        busiCartDetailItem.setProdPrice(bp.getPrice());
                        busiCartDetailItem.setTotalPrice(bp.getPrice());
                        busiCartDetailItem.setStandy1(bp.getImgUrl()); //图片相对地址';
                        busiCartDetailItem.setStandy2(bp.getProdDesc()); //产品描述
                        busiCartDetailItem.setStandy3(Dict.YesOrNo.Yes.getCode()); //数据状态:Y:有效N:无效
                        //产品状态码 1000:新建;2000:准备生成订单;3000:已生成订单'
                        busiCartDetailItem.setStandy4(Dict.BusiCaer.CartItemStatusCode.NEW.getCode());
                        busiCartDetailItem.setCategoryName("");//产品分类
                        logger.info("购物车增加清单项1:",JSONObject.toJSONString(busiCartDetailItem));
                        Boolean b = busiCartDetailItemService.insert(busiCartDetailItem);

                    }
                }else{
                    //该用户的购物车没有任何产品
                   //BusiCartDetailItem busiCartDetailItem1 = new BusiCartDetailItem();
//                    String sql ="SELECT (SEQ_BUSI_CART_DETAIL_ITEM.NEXTVAL) ID FROM DUAL";
//                    Map<String, Object> resultMap = jdbcTemplate.queryForMap(sql);
//                    Object id2 = resultMap.get("ID");
                    busiCartDetailItem.setId(getCartDetailItemId());
                    busiCartDetailItem.setSum(1+"");
                    busiCartDetailItem.setCartId(currUserCart.getId());
                    busiCartDetailItem.setProdId(bp.getId());
                    busiCartDetailItem.setProdName(bp.getZhName());
                    busiCartDetailItem.setProdPrice(bp.getPrice());
                    busiCartDetailItem.setTotalPrice(bp.getPrice());
                    busiCartDetailItem.setStandy1(bp.getImgUrl()); //图片相对地址';
                    busiCartDetailItem.setStandy2(bp.getProdDesc()); //产品描述
                    busiCartDetailItem.setStandy3(Dict.YesOrNo.Yes.getCode()); //数据状态:Y:有效N:无效
                    //产品状态码 1000:新建;2000:准备生成订单;3000:已生成订单'
                    busiCartDetailItem.setStandy4(Dict.BusiCaer.CartItemStatusCode.NEW.getCode());
                    busiCartDetailItem.setCategoryName("");//产品分类
                    logger.info("购物车增加清单项2:",JSONObject.toJSONString(busiCartDetailItem));
                    Boolean b = busiCartDetailItemService.insert(busiCartDetailItem);

                }
            }else{
                //没有购物车，为当前用户创建购物车并添加到购物车
//                String sql ="SELECT (SEQ_BUSI_CART.NEXTVAL) ID FROM DUAL";
//                Map<String, Object> resultMap = jdbcTemplate.queryForMap(sql);
//                Object cartId = resultMap.get("ID");
                String cartId = getCartId();
                busiCart.setId(cartId);
                busiCart.setDataFrom("sys");
//                busiCart.setCreator(cuurMiMember.getMemberNo());
//                busiCart.setUpdator(cuurMiMember.getMemberNo());
                busiCart.setCreateTime(DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
                busiCart.setDataStatus(Dict.YesOrNo.Yes.getCode());
                busiCart.setProdDesc("描述");
                busiCart.setUpdateTime(DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
                busiCart.setMemberNo(cuurMiMember.getMemberNo());
                busiCart.setProdId("0");
                busiCart.setTotalAmount("0.00");
                busiCart.setMemo("备注");
                Boolean b =  busiCartService.insert(busiCart);
                logger.info("添加购物车:",JSONObject.toJSONString(busiCart));
                if(b){ //创建购物车成功，把产品加入到该购物车
                    currUserCart = busiCartService.selectOne(ew);
                    BusiCartDetailItem busiCartDetailItem2 = new BusiCartDetailItem();
                    busiCartDetailItem2.setId(getCartDetailItemId());
                    busiCartDetailItem2.setSum(1+"");
                    busiCartDetailItem2.setCartId(currUserCart.getId());
                    busiCartDetailItem2.setProdId(bp.getId());
                    busiCartDetailItem2.setProdName(bp.getZhName());
                    busiCartDetailItem2.setProdPrice(bp.getPrice());
                    busiCartDetailItem2.setTotalPrice(bp.getPrice());
                    busiCartDetailItem2.setStandy1(bp.getImgUrl()); //图片相对地址';
                    busiCartDetailItem2.setStandy2(bp.getProdDesc()); //产品描述
                    busiCartDetailItem2.setStandy3(Dict.YesOrNo.Yes.getCode()); //数据状态:Y:有效N:无效
                    //产品状态码 1000:新建;2000:准备生成订单;3000:已生成订单'
                    busiCartDetailItem2.setStandy4(Dict.BusiCaer.CartItemStatusCode.NEW.getCode());
                    busiCartDetailItem2.setCategoryName("");//产品分类
                    logger.info("添加购物车清单项3:",JSONObject.toJSONString(busiCartDetailItem2));
                    Boolean flag = busiCartDetailItemService.insert(busiCartDetailItem2);
                }
            }
            //跳转到购物车列表页面
            currUserCart = busiCartService.selectOne(ew);
            request.setAttribute("currUserCart",currUserCart);
            EntityWrapper<BusiCartDetailItem> ew1 = new EntityWrapper();
            BusiCartDetailItem busiCartDetailItem = new BusiCartDetailItem();
            //查询状态为有效的清单项
            busiCartDetailItem.setStandy3(Dict.YesOrNo.Yes.getCode());
            //查询产品状态码为1000的清单项
            busiCartDetailItem.setStandy4(Dict.BusiCaer.CartItemStatusCode.NEW.getCode());
            busiCartDetailItem.setCartId(currUserCart.getId());
            ew1.setEntity(busiCartDetailItem);
            List<BusiCartDetailItem> busiCartDetailItems = busiCartDetailItemService.selectList(ew1);
            request.setAttribute("busiCartDetailItems",busiCartDetailItems);
            request.setAttribute("busiCartId",currUserCart.getId());
            //3.移除session中的Token
            request.getSession().removeAttribute("verifySuocrePage");
            return "/cart/shoppingCart";
        }else{
            //没有登录了，跳转到登录页面，登录完成跳回原来页面
            request.setAttribute("busiProductId" ,id);
            return "/cart/login";
        }
    }


    @RequestMapping("/shoppingCartList_page")
    public String shoppingCartList_page(HttpServletRequest request){
        //判断是否登录
        HttpSession session = request.getSession();
        MiMember member = (MiMember)session.getAttribute("cuurMiMember");
        if(null == member){
            //没有登录了，跳转到登录页面，登录完成跳回原来页面
            return "/cart/cartList_login";
        }
        //登录了，跳转到购物车列表页面
        //获取会员的购物车
        EntityWrapper<BusiCart> enW = new EntityWrapper<>();
        BusiCart busiCart = new BusiCart();
        busiCart.setMemberNo(member.getMemberNo());
        enW.setEntity(busiCart);
        busiCart = busiCartService.selectOne(enW);
        //获取会员的购物清单项
        EntityWrapper<BusiCartDetailItem> ew = new EntityWrapper<>();
        BusiCartDetailItem busiCartDetailItem = new BusiCartDetailItem();
        busiCartDetailItem.setCartId(busiCart.getId());
        //查询状态为有效的清单项
        busiCartDetailItem.setStandy3(Dict.YesOrNo.Yes.getCode());
        //查询产品状态码为1000的清单项
        busiCartDetailItem.setStandy4(Dict.BusiCaer.CartItemStatusCode.NEW.getCode());
        ew.setEntity(busiCartDetailItem);
        List<BusiCartDetailItem> busiCartDetailItemList = busiCartDetailItemService.selectList(ew);
        request.setAttribute("busiCartDetailItems",busiCartDetailItemList);
        request.setAttribute("busiCartId",busiCart.getId());
        return "/cart/shoppingCart";
    }

    /**
     * 购物车结算
     * @param request
     * @return
     */
    @RequestMapping("/settlement")
    @ResponseBody
    public Object settlement(HttpServletRequest request, HttpServletResponse response) {
//        response.setCharacterEncoding(Charsets.UTF_8.toString());
//        response.setHeader("Content-Type","text/html;charset=utf-8");
        //获取请求数据
        String catrId = request.getParameter("catrId");
        String catrItemIds = request.getParameter("catrItemIds");
        String totalAmount = request.getParameter("totalAmount");
        String counts = request.getParameter("counts");
        String[] ItemIds = catrItemIds.split(",");
        String[] ItemINums = counts.split(",");
        Boolean b =false;
        try {
            logger.info("catrId:[{}]-totalAmount:[{}]-ItemIds:[{}]-ItemINums:[{}]",catrId,totalAmount,ItemIds,ItemINums);
             b = busiCartService.handleCartData(catrId,totalAmount,ItemIds,ItemINums);
        }catch (Exception  e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        if(!b){
            return write2Json(catrId, Boolean.FALSE,"处理失败!", null);
        }
        return write2Json(catrId, Boolean.TRUE,"处理成功!", null);

//        PrintWriter writer = response.getWriter();
//        writer.write(JSONObject.toJSONString(write2Json(null, Boolean.TRUE,"处理成功!", null)));
    }

    @RequestMapping("/cart_settlement")
    @ResponseBody
    public Object  cart_settlement(HttpServletRequest request, HttpServletResponse response){
//        response.setCharacterEncoding(Charsets.UTF_8.toString());
//        response.setHeader("Content-Type","text/html;charset=utf-8");
        //获取请求数据
        String catrId = request.getParameter("catrId");
        String catrItemIds = request.getParameter("catrItemIds");
        String totalAmount = request.getParameter("totalAmount");
        String[] ItemIds = catrItemIds.split(",");
        System.out.println(catrId);
        System.out.println(catrItemIds);
        System.out.println(totalAmount);
        System.out.println(ItemIds);
        EntityWrapper<BusiCart> ew = new EntityWrapper<>();
        BusiCart busiCart = new BusiCart();
        busiCart.setId(catrId);
        ew.setEntity(busiCart);
        busiCart = busiCartService.selectOne(ew);
        busiCart.setTotalAmount(totalAmount);
        ew.setEntity(busiCart);
        busiCartService.update(busiCart,ew);
        EntityWrapper<BusiCartDetailItem> ew1 = new EntityWrapper<>();
        BusiCartDetailItem busiCartDetailItem = new BusiCartDetailItem();
        busiCartDetailItem.setCartId(busiCart.getId());
        ew1.setEntity(busiCartDetailItem);
        List<BusiCartDetailItem> busiCartDetailItemList = busiCartDetailItemService.selectList(ew1);
        for (BusiCartDetailItem item: busiCartDetailItemList) {
            String itemId =  item.getId();
            for (String id:ItemIds) {
                if(id.equals(itemId)){
                    item.setStandy4("2000");
                }
            }
        }
        return write2Json(null, Boolean.TRUE,"登陆成功!", null);
    }

    public String getCartId(){
        String sql ="SELECT (SEQ_BUSI_CART.NEXTVAL) ID FROM DUAL";
        Map<String, Object> resultMap = jdbcTemplate.queryForMap(sql);
        Object cartId = resultMap.get("ID");
        return cartId.toString();
    }

    public String getCartDetailItemId(){
        String sql ="SELECT (SEQ_BUSI_CART_DETAIL_ITEM.NEXTVAL) ID FROM DUAL";
        Map<String, Object> resultMap = jdbcTemplate.queryForMap(sql);
        Object id = resultMap.get("ID");
        return id.toString();
    }


}
